<?php
require_once 'Datatype_integer.php';

class Datatype_file extends Datatype_integer
{

    private $_file;
    private $_fileArr;
    private $_myFile;

    public function __construct(EDO_object_basic $owner, $config = array())
	{
		parent::__construct($owner, $config);

		$this->getOwner()->attach($this, 'onSave', '_save');
		$this->getOwner()->attach($this, 'onInsert', '_save');

		$this->getOwner()->attach($this, 'onDelete', '_delete');

		$this->getOwner()->attach($this, 'onSaveSuccess', '_saveSuccess');
        $this->getOwner()->attach($this, 'onInsertSuccess', '_saveSuccess');
	}


	public function getFile()
	{
	    $file = $this->getOwner()->getHandler()->get('file');
	    $file->fetch($this->getValue());


	    return $file;
	}


    public function validate($value)
    {

       if(is_array($value))
        {
            if(isset($_FILES[$value['field']]))
            {
                $myFile = $_FILES[$value['field']];

                if($myFile['error'] == 0)
                    return $myFile;
                else
                    return null;
            }

            return null;
        }


        if(is_numeric($value))
            return $value;

        if(is_null($value))
            return null;


        return false;


    }



    public function _save()
    {

        if($value = $this->getValue() AND is_array($value))
        {
            $file = $this->getValue();

            $this->_fileArr = $file;

            $this->_file = $this->getOwner()->getHandler()->get('file');
            $this->_file->edoid = $this->_file->ldb->nextId('edoid');

            $this->_file->name = $file['name'];
            $this->_file->type = $file['type'];
            $this->_file->size = $file['size'];

            $this->setValue($this->_file->edoid);
        }




        return true;

    }


    public function _saveSuccess()
    {


        if($this->_file)
        {

            if($this->_file->isFetched())
            {
                // $this->_file->save();
            }
            else
            {
                $success = $this->_file->insert(false);

                if(!$success)
                {
                    // errors? we check for NO ERRORS!1!

                }

                $path = LEAD::registry('application')->root['customer'] . '/data/files/' . $this->_file->edoid;


                move_uploaded_file($this->_fileArr['tmp_name'], $path);


            }

        }




        return true;
    }


    public function _delete()
    {
        $file = $this->getFile();
        if($file)
            $file->delete();

        $path = LEAD::registry('application')->root['customer'] . '/data/files/' . $this->GetValue();
        if(is_file($path))
            unlink($path);
    }


}